/**
 * 
 */
package com.vector.ding.commons.util.file;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;

/**
 * @author vector
 *
 */
public final class UploadUtil {
	
	public static boolean validateFileType(File file, String... requiredTypes) {
		if (file.isDirectory())
			return true;
		
		String fileName = file.getName();
		if (StringUtil.isEmpty(fileName))
			return false;
		boolean result = false;
		for (String type: requiredTypes) {
			if (fileName.endsWith(type)) {
				result = true;
				continue;
			}
		}
		return result;
	}
	
	public static File getUploadFile(
			HttpServletRequest request, HttpServletResponse response,
			String uploadFilePath) {
		List<File> fileList = getUploadFiles(request, response, uploadFilePath);
		return fileList.isEmpty() ? null : fileList.get(0);
	}

	public static List<File> getUploadFiles(
			HttpServletRequest request, HttpServletResponse response,
			String uploadFilePath) {
		List<File> fileList = new LinkedList<File>();
		DiskFileItemFactory df = new DiskFileItemFactory();
		/*File tempFolder = new File(Constant.Upload.TEMP_PATH);
		if (!tempFolder.exists())
			tempFolder.mkdirs();
		df.setRepository(tempFolder);*/
		ServletFileUpload upload = new ServletFileUpload(df);//声明解析request的对象
		
		try {
			List<FileItem> fileItems = upload.parseRequest(request);
			if (CollectionUtil.isEmpty(fileItems))
				return fileList;
			
			for (FileItem fileItem: fileItems) {
				if (fileItem.isFormField())
					continue;
				String fileName = fileItem.getName();
				fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
				int pointIdx = fileName.lastIndexOf(".");
				String fileSuffix = "";
				if (pointIdx != -1) {
					fileSuffix = fileName.substring(pointIdx);
					fileName = fileName.substring(0, pointIdx);
				}
				fileName = StringUtil.wrapString(fileName, "", StringUtil.getTimeStamp());
				File file = new File(uploadFilePath, StringUtil.wrapString(fileName, "", fileSuffix));
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				fileItem.write(file);

				fileList.add(file);
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
		return fileList;
	}
}
